// 文件上传和预览处理
document.querySelectorAll('input[type="file"]').forEach(input => {
    input.addEventListener('change', handleFileSelect);
});

document.getElementById('uploadArea').addEventListener('dragover', function(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
});

document.getElementById('uploadArea').addEventListener('dragleave', function(e) {
    e.currentTarget.classList.remove('dragover');
});

document.getElementById('uploadArea').addEventListener('drop', function(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = e.dataTransfer.files;
    if (files.length) {
        handleFileSelect({ target: { files } });
    }
});

function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    const previewArea = document.getElementById('originalPreview');
    const enhancedPreview = document.getElementById('enhancedPreview');

    // 清除之前的增强效果
    enhancedPreview.innerHTML = '';

    reader.onloadstart = function() {
        document.getElementById('uploadProgress').style.display = 'block';
    };

    reader.onprogress = function(e) {
        if (e.lengthComputable) {
            const percentLoaded = Math.round((e.loaded / e.total) * 100);
            document.getElementById('uploadProgress').value = percentLoaded;
        }
    };

    reader.onload = function(e) {
        const img = document.createElement('img');
        img.src = e.target.result;
        previewArea.innerHTML = '';
        previewArea.appendChild(img);
        document.getElementById('uploadProgress').style.display = 'none';
    };

    reader.readAsDataURL(file);
}

// 导航处理
document.querySelectorAll('.sidebar a').forEach(link => {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        const targetId = this.getAttribute('href').substring(1);
        
        // 更新活动状态
        document.querySelectorAll('.sidebar a').forEach(a => a.classList.remove('active'));
        this.classList.add('active');
        
        // 显示对应部分
        document.querySelectorAll('main section').forEach(section => {
            section.style.display = 'none';
        });
        document.getElementById(targetId).style.display = 'block';
    });
});

// 功能实现
let enhancementInterval;
let enhancementPaused = false;
let enhancementProgressValue = 0;

function enhanceImage() {
    const originalPreview = document.getElementById('originalPreview');
    const enhancedPreview = document.getElementById('enhancedPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传图像文件');
        return;
    }

    const sharpness = document.getElementById('sharpness').value;
    const contrast = document.getElementById('contrast').value;

    console.log(`增强图像处理中... 锐化程度: ${sharpness}, 对比度: ${contrast}`);
    enhancementProgressValue = 0;
    document.getElementById('enhancementProgress').style.display = 'block';
    enhancementInterval = setInterval(() => {
        if (!enhancementPaused) {
            enhancementProgressValue += 10;
            document.getElementById('enhancementProgress').value = enhancementProgressValue;
            if (enhancementProgressValue >= 100) {
                clearInterval(enhancementInterval);
                document.getElementById('enhancementProgress').style.display = 'none';
                const originalContent = originalPreview.firstChild.cloneNode(true);
                enhancedPreview.innerHTML = '';
                enhancedPreview.appendChild(originalContent);
                alert('图像增强完成');
            }
        }
    }, 500);
}

function enhanceVideo() {
    const originalPreview = document.getElementById('originalPreview');
    const enhancedPreview = document.getElementById('enhancedPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传视频文件');
        return;
    }

    const sharpness = document.getElementById('sharpness').value;
    const contrast = document.getElementById('contrast').value;

    console.log(`增强视频处理中... 锐化程度: ${sharpness}, 对比度: ${contrast}`);
    enhancementProgressValue = 0;
    document.getElementById('enhancementProgress').style.display = 'block';
    enhancementInterval = setInterval(() => {
        if (!enhancementPaused) {
            enhancementProgressValue += 10;
            document.getElementById('enhancementProgress').value = enhancementProgressValue;
            if (enhancementProgressValue >= 100) {
                clearInterval(enhancementInterval);
                document.getElementById('enhancementProgress').style.display = 'none';
                const originalContent = originalPreview.firstChild.cloneNode(true);
                enhancedPreview.innerHTML = '';
                enhancedPreview.appendChild(originalContent);
                alert('视频增强完成');
            }
        }
    }, 500);
}

function pauseEnhancement() {
    enhancementPaused = true;
    console.log('增强处理已暂停');
}

function resumeEnhancement() {
    enhancementPaused = false;
    console.log('增强处理已继续');
}

function downloadEnhancedResult() {
    const enhancedPreview = document.getElementById('enhancedPreview');
    if (!enhancedPreview.firstChild) {
        alert('没有可下载的增强结果');
        return;
    }

    const content = enhancedPreview.firstChild;
    if (content.tagName === 'IMG') {
        const link = document.createElement('a');
        link.href = content.src;
        link.download = 'enhanced_image.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        console.log('图像已下载');
    } else if (content.tagName === 'VIDEO') {
        alert('视频下载功能尚未实现');
    }
}

document.getElementById('derainInput').addEventListener('change', handleDerainFileSelect);

document.getElementById('derainUploadArea').addEventListener('dragover', function(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
});

document.getElementById('derainUploadArea').addEventListener('dragleave', function(e) {
    e.currentTarget.classList.remove('dragover');
});

document.getElementById('derainUploadArea').addEventListener('drop', function(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = e.dataTransfer.files;
    if (files.length) {
        handleDerainFileSelect({ target: { files } });
    }
});

function handleDerainFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    const previewArea = document.getElementById('derainOriginalPreview');
    const enhancedPreview = document.getElementById('derainEnhancedPreview');

    // 清除之前的去雨去雾效果
    enhancedPreview.innerHTML = '';

    reader.onloadstart = function() {
        document.getElementById('derainUploadProgress').style.display = 'block';
    };

    reader.onprogress = function(e) {
        if (e.lengthComputable) {
            const percentLoaded = Math.round((e.loaded / e.total) * 100);
            document.getElementById('derainUploadProgress').value = percentLoaded;
        }
    };

    reader.onload = function(e) {
        if (file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.src = e.target.result;
            previewArea.innerHTML = '';
            previewArea.appendChild(img);
        } else if (file.type.startsWith('video/')) {
            const video = document.createElement('video');
            video.controls = true;
            video.src = e.target.result;
            previewArea.innerHTML = '';
            previewArea.appendChild(video);
        }
        document.getElementById('derainUploadProgress').style.display = 'none';
    };

    reader.readAsDataURL(file);
}

let processingInterval;
let processingPaused = false;
let processingProgressValue = 0;

function removeRain() {
    const originalPreview = document.getElementById('derainOriginalPreview');
    const enhancedPreview = document.getElementById('derainEnhancedPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传文件');
        return;
    }

    const rainIntensity = document.getElementById('rainIntensity').value;

    console.log(`去雨处理中... 去雨强度: ${rainIntensity}`);
    processingProgressValue = 0;
    document.getElementById('processingProgress').style.display = 'block';
    processingInterval = setInterval(() => {
        if (!processingPaused) {
            processingProgressValue += 10;
            document.getElementById('processingProgress').value = processingProgressValue;
            if (processingProgressValue >= 100) {
                clearInterval(processingInterval);
                document.getElementById('processingProgress').style.display = 'none';
                const originalContent = originalPreview.firstChild.cloneNode(true);
                enhancedPreview.innerHTML = '';
                enhancedPreview.appendChild(originalContent);
                alert('去雨处理完成');
            }
        }
    }, 500);
}

function removeFog() {
    const originalPreview = document.getElementById('derainOriginalPreview');
    const enhancedPreview = document.getElementById('derainEnhancedPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传文件');
        return;
    }

    const fogIntensity = document.getElementById('fogIntensity').value;

    console.log(`去雾处理中... 去雾强度: ${fogIntensity}`);
    processingProgressValue = 0;
    document.getElementById('processingProgress').style.display = 'block';
    processingInterval = setInterval(() => {
        if (!processingPaused) {
            processingProgressValue += 10;
            document.getElementById('processingProgress').value = processingProgressValue;
            if (processingProgressValue >= 100) {
                clearInterval(processingInterval);
                document.getElementById('processingProgress').style.display = 'none';
                const originalContent = originalPreview.firstChild.cloneNode(true);
                enhancedPreview.innerHTML = '';
                enhancedPreview.appendChild(originalContent);
                alert('去雾处理完成');
            }
        }
    }, 500);
}

function pauseProcessing() {
    processingPaused = true;
    console.log('处理已暂停');
}

function resumeProcessing() {
    processingPaused = false;
    console.log('处理已继续');
}

function downloadProcessedVideo() {
    const enhancedPreview = document.getElementById('derainEnhancedPreview');
    if (!enhancedPreview.firstChild) {
        alert('没有可下载的处理结果');
        return;
    }

    const content = enhancedPreview.firstChild;
    if (content.tagName === 'IMG') {
        const link = document.createElement('a');
        link.href = content.src;
        link.download = 'processed_image.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        console.log('图像已下载');
    } else if (content.tagName === 'VIDEO') {
        alert('视频下载功能尚未实现');
    }
}

// 页面加载时显示第一个部分
window.onload = function() {
    document.querySelector('main section').style.display = 'block';
};

function detectOcclusion() {
    alert("遮挡检测功能尚未实现");
    // 在这里添加遮挡检测的逻辑
}

function detectSceneChange() {
    alert("场景变更检测功能尚未实现");
    // 在这里添加场景变更检测的逻辑
}

function evaluateQuality() {
    alert("图像/视频质量评价功能尚未实现");
    // 在这里添加质量评价的逻辑
}

function superResolution() {
    alert("超分辨率重建功能尚未实现");
    // 在这里添加超分辨率重建的逻辑
}

// 添加遮挡检测相关的变量
let detectionInterval;
let detectionPaused = false;
let detectionProgressValue = 0;

// 添加文件上传处理
document.getElementById('detectionInput').addEventListener('change', handleDetectionFileSelect);

document.getElementById('detectionUploadArea').addEventListener('dragover', function(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
});

document.getElementById('detectionUploadArea').addEventListener('dragleave', function(e) {
    e.currentTarget.classList.remove('dragover');
});

document.getElementById('detectionUploadArea').addEventListener('drop', function(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = e.dataTransfer.files;
    if (files.length) {
        handleDetectionFileSelect({ target: { files } });
    }
});

function handleDetectionFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    const previewArea = document.getElementById('detectionOriginalPreview');
    const resultPreview = document.getElementById('detectionResultPreview');

    // 清除之前的检测结果
    resultPreview.innerHTML = '';

    reader.onloadstart = function() {
        document.getElementById('detectionUploadProgress').style.display = 'block';
    };

    reader.onprogress = function(e) {
        if (e.lengthComputable) {
            const percentLoaded = Math.round((e.loaded / e.total) * 100);
            document.getElementById('detectionUploadProgress').value = percentLoaded;
        }
    };

    reader.onload = function(e) {
        if (file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.src = e.target.result;
            previewArea.innerHTML = '';
            previewArea.appendChild(img);
        } else if (file.type.startsWith('video/')) {
            const video = document.createElement('video');
            video.controls = true;
            video.src = e.target.result;
            previewArea.innerHTML = '';
            previewArea.appendChild(video);
        }
        document.getElementById('detectionUploadProgress').style.display = 'none';
    };

    reader.readAsDataURL(file);
}

function startDetection() {
    const originalPreview = document.getElementById('detectionOriginalPreview');
    const resultPreview = document.getElementById('detectionResultPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传文件');
        return;
    }

    const sensitivity = document.getElementById('sensitivity').value;
    const threshold = document.getElementById('threshold').value;

    console.log(`开始遮挡检测... 灵敏度: ${sensitivity}, 阈值: ${threshold}`);
    detectionProgressValue = 0;
    document.getElementById('detectionProgress').style.display = 'block';

    // 模拟检测过程
    detectionInterval = setInterval(() => {
        if (!detectionPaused) {
            detectionProgressValue += 10;
            document.getElementById('detectionProgress').value = detectionProgressValue;
            
            // 更新检测信息
            updateDetectionStats(detectionProgressValue);

            if (detectionProgressValue >= 100) {
                clearInterval(detectionInterval);
                document.getElementById('detectionProgress').style.display = 'none';
                
                // 显示检测结果
                const originalContent = originalPreview.firstChild.cloneNode(true);
                resultPreview.innerHTML = '';
                resultPreview.appendChild(originalContent);
                
                // 在结果上添加遮挡标记（这里仅作示例）
                if (resultPreview.firstChild.tagName === 'IMG') {
                    addOcclusionMarkers(resultPreview);
                }
                
                alert('遮挡检测完成');
            }
        }
    }, 500);
}

function updateDetectionStats(progress) {
    // 模拟更新检测统计信息
    const occlusionArea = Math.round(Math.random() * 30);
    const occlusionDuration = Math.round(progress / 10);
    
    document.getElementById('occlusionArea').textContent = `${occlusionArea}%`;
    document.getElementById('occlusionDuration').textContent = `${occlusionDuration}秒`;
}

function addOcclusionMarkers(container) {
    // 模拟添加遮挡标记
    const marker = document.createElement('div');
    marker.className = 'occlusion-marker';
    marker.style.position = 'absolute';
    marker.style.border = '2px solid red';
    marker.style.backgroundColor = 'rgba(255, 0, 0, 0.2)';
    marker.style.width = '100px';
    marker.style.height = '100px';
    container.style.position = 'relative';
    container.appendChild(marker);
}

function pauseDetection() {
    detectionPaused = true;
    console.log('检测已暂停');
}

function resumeDetection() {
    detectionPaused = false;
    console.log('检测已继续');
}

function downloadDetectionResult() {
    const resultPreview = document.getElementById('detectionResultPreview');
    if (!resultPreview.firstChild) {
        alert('没有可下载的检测结果');
        return;
    }

    const content = resultPreview.firstChild;
    if (content.tagName === 'IMG') {
        const link = document.createElement('a');
        link.href = content.src;
        link.download = 'detection_result.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        console.log('检测结果已下载');
    } else if (content.tagName === 'VIDEO') {
        alert('视频结果下载功能尚未实现');
    }
}

// 添加场景变更检测相关的变量
let sceneInterval;
let scenePaused = false;
let sceneProgressValue = 0;
let sceneMarkers = [];

// 添加文件上传处理
document.getElementById('sceneChangeInput').addEventListener('change', handleSceneFileSelect);

document.getElementById('sceneChangeUploadArea').addEventListener('dragover', function(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
});

document.getElementById('sceneChangeUploadArea').addEventListener('dragleave', function(e) {
    e.currentTarget.classList.remove('dragover');
});

document.getElementById('sceneChangeUploadArea').addEventListener('drop', function(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = e.dataTransfer.files;
    if (files.length) {
        handleSceneFileSelect({ target: { files } });
    }
});

function handleSceneFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    if (!file.type.startsWith('video/')) {
        alert('请上传视频文件');
        return;
    }

    const reader = new FileReader();
    const previewArea = document.getElementById('sceneOriginalPreview');
    const resultPreview = document.getElementById('sceneResultPreview');

    // 清除之前的检测结果
    resultPreview.innerHTML = '';
    document.querySelector('.timeline-markers').innerHTML = '';
    sceneMarkers = [];

    reader.onloadstart = function() {
        document.getElementById('sceneChangeUploadProgress').style.display = 'block';
    };

    reader.onprogress = function(e) {
        if (e.lengthComputable) {
            const percentLoaded = Math.round((e.loaded / e.total) * 100);
            document.getElementById('sceneChangeUploadProgress').value = percentLoaded;
        }
    };

    reader.onload = function(e) {
        const video = document.createElement('video');
        video.controls = true;
        video.src = e.target.result;
        previewArea.innerHTML = '';
        previewArea.appendChild(video);
        document.getElementById('sceneChangeUploadProgress').style.display = 'none';
    };

    reader.readAsDataURL(file);
}

function startSceneDetection() {
    const originalPreview = document.getElementById('sceneOriginalPreview');
    const resultPreview = document.getElementById('sceneResultPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传视频文件');
        return;
    }

    const threshold = document.getElementById('sceneThreshold').value;
    const minDuration = document.getElementById('minDuration').value;

    console.log(`开始场景变更检测... 阈值: ${threshold}, 最小持续时间: ${minDuration}秒`);
    sceneProgressValue = 0;
    document.getElementById('sceneProgress').style.display = 'block';

    // 清除之前的标记
    document.querySelector('.timeline-markers').innerHTML = '';
    sceneMarkers = [];

    sceneInterval = setInterval(() => {
        if (!scenePaused) {
            sceneProgressValue += 10;
            document.getElementById('sceneProgress').value = sceneProgressValue;
            
            // 更新检测信息
            updateSceneStats(sceneProgressValue);
            
            // 添加场景标记
            if (sceneProgressValue % 20 === 0) {
                addSceneMarker(sceneProgressValue);
            }

            if (sceneProgressValue >= 100) {
                clearInterval(sceneInterval);
                document.getElementById('sceneProgress').style.display = 'none';
                
                // 显示检测结果
                const originalContent = originalPreview.firstChild.cloneNode(true);
                resultPreview.innerHTML = '';
                resultPreview.appendChild(originalContent);
                
                alert('场景变更检测完成');
            }
        }
    }, 500);
}

function updateSceneStats(progress) {
    const sceneCount = Math.floor(progress / 20);
    const avgDuration = sceneCount > 0 ? Math.round((progress / sceneCount) * 0.1) : 0;
    
    document.getElementById('sceneCount').textContent = sceneCount;
    document.getElementById('avgSceneDuration').textContent = `${avgDuration}秒`;
}

function addSceneMarker(progress) {
    const marker = document.createElement('div');
    marker.className = 'scene-marker';
    marker.style.left = `${progress}%`;
    marker.setAttribute('data-time', `${(progress / 10).toFixed(1)}秒`);
    
    document.querySelector('.timeline-markers').appendChild(marker);
    sceneMarkers.push({
        time: progress / 10,
        element: marker
    });
}

function pauseSceneDetection() {
    scenePaused = true;
    console.log('场景检测已暂停');
}

function resumeSceneDetection() {
    scenePaused = false;
    console.log('场景检测已继续');
}

function downloadSceneResult() {
    const resultPreview = document.getElementById('sceneResultPreview');
    if (!resultPreview.firstChild) {
        alert('没有可下载的检测结果');
        return;
    }

    // 创建场景变更报告
    const report = {
        sceneCount: document.getElementById('sceneCount').textContent,
        avgDuration: document.getElementById('avgSceneDuration').textContent,
        markers: sceneMarkers.map(marker => ({
            time: marker.time
        }))
    };

    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'scene_change_report.json';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    console.log('场景检测报告已下载');
}

// 添加质量评价相关的变量
let evaluationInterval;
let evaluationPaused = false;
let evaluationProgressValue = 0;

// 添加文件上传处理
document.getElementById('evaluationInput').addEventListener('change', handleEvaluationFileSelect);

document.getElementById('evaluationUploadArea').addEventListener('dragover', function(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
});

document.getElementById('evaluationUploadArea').addEventListener('dragleave', function(e) {
    e.currentTarget.classList.remove('dragover');
});

document.getElementById('evaluationUploadArea').addEventListener('drop', function(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = e.dataTransfer.files;
    if (files.length) {
        handleEvaluationFileSelect({ target: { files } });
    }
});

function handleEvaluationFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    const previewArea = document.getElementById('evaluationOriginalPreview');

    reader.onloadstart = function() {
        document.getElementById('evaluationUploadProgress').style.display = 'block';
    };

    reader.onprogress = function(e) {
        if (e.lengthComputable) {
            const percentLoaded = Math.round((e.loaded / e.total) * 100);
            document.getElementById('evaluationUploadProgress').value = percentLoaded;
        }
    };

    reader.onload = function(e) {
        if (file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.src = e.target.result;
            previewArea.innerHTML = '';
            previewArea.appendChild(img);
            document.getElementById('fileInfo').textContent = `图像文件: ${file.name}`;
        } else if (file.type.startsWith('video/')) {
            const video = document.createElement('video');
            video.controls = true;
            video.src = e.target.result;
            previewArea.innerHTML = '';
            previewArea.appendChild(video);
            document.getElementById('fileInfo').textContent = `视频文件: ${file.name}`;
        }
        document.getElementById('evaluationUploadProgress').style.display = 'none';
    };

    reader.readAsDataURL(file);
}

function startEvaluation() {
    const originalPreview = document.getElementById('evaluationOriginalPreview');
    if (!originalPreview.firstChild) {
        alert('请先上传文件');
        return;
    }

    const method = document.getElementById('evaluationMethod').value;
    document.getElementById('methodInfo').textContent = document.getElementById('evaluationMethod').options[document.getElementById('evaluationMethod').selectedIndex].text;

    console.log(`开始质量评价... 评价方法: ${method}`);
    evaluationProgressValue = 0;
    document.getElementById('evaluationProgress').style.display = 'block';

    evaluationInterval = setInterval(() => {
        if (!evaluationPaused) {
            evaluationProgressValue += 10;
            document.getElementById('evaluationProgress').value = evaluationProgressValue;
            
            // 更新评分
            updateEvaluationScores(evaluationProgressValue);

            if (evaluationProgressValue >= 100) {
                clearInterval(evaluationInterval);
                document.getElementById('evaluationProgress').style.display = 'none';
                document.getElementById('processTime').textContent = '2.5秒';
                alert('质量评价完成');
            }
        }
    }, 500);
}

function updateEvaluationScores(progress) {
    // 模拟评分更新
    const overallScore = Math.round((Math.random() * 20 + 80) * progress / 100);
    const clarity = Math.round((Math.random() * 20 + 80) * progress / 100);
    const color = Math.round((Math.random() * 20 + 80) * progress / 100);
    const noise = Math.round((Math.random() * 20 + 80) * progress / 100);
    const compression = Math.round((Math.random() * 20 + 80) * progress / 100);
    
    document.getElementById('overallScore').textContent = overallScore;
    document.getElementById('clarityScore').textContent = clarity;
    document.getElementById('colorScore').textContent = color;
    document.getElementById('noiseScore').textContent = noise;
    document.getElementById('compressionScore').textContent = compression;
}

function pauseEvaluation() {
    evaluationPaused = true;
    console.log('评价已暂停');
}

function resumeEvaluation() {
    evaluationPaused = false;
    console.log('评价已继续');
}

function downloadEvaluationReport() {
    const scores = {
        overall: document.getElementById('overallScore').textContent,
        clarity: document.getElementById('clarityScore').textContent,
        color: document.getElementById('colorScore').textContent,
        noise: document.getElementById('noiseScore').textContent,
        compression: document.getElementById('compressionScore').textContent,
        fileInfo: document.getElementById('fileInfo').textContent,
        method: document.getElementById('methodInfo').textContent,
        processTime: document.getElementById('processTime').textContent
    };

    const report = {
        title: "质量评价报告",
        timestamp: new Date().toLocaleString(),
        scores: scores
    };

    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'quality_evaluation_report.json';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    console.log('评价报告已下载');
}

// 添加超分辨率重建相关的变量
let superResolutionInterval;
let superResolutionPaused = false;
let superResolutionProgressValue = 0;

// 添加文件上传处理
document.getElementById('superResolutionInput').addEventListener('change', handleSuperResolutionFileSelect);

document.getElementById('superResolutionUploadArea').addEventListener('dragover', function(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
});

document.getElementById('superResolutionUploadArea').addEventListener('dragleave', function(e) {
    e.currentTarget.classList.remove('dragover');
});

document.getElementById('superResolutionUploadArea').addEventListener('drop', function(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = e.dataTransfer.files;
    if (files.length) {
        handleSuperResolutionFileSelect({ target: { files } });
    }
});

function handleSuperResolutionFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    const previewArea = document.getElementById('superResolutionOriginalPreview');
    const resultPreview = document.getElementById('superResolutionResultPreview');

    // 清除之前的重建结果
    resultPreview.innerHTML = '';

    reader.onloadstart = function() {
        document.getElementById('superResolutionUploadProgress').style.display = 'block';
    };

    reader.onprogress = function(e) {
        if (e.lengthComputable) {
            const percentLoaded = Math.round((e.loaded / e.total) * 100);
            document.getElementById('superResolutionUploadProgress').value = percentLoaded;
        }
    };

    reader.onload = function(e) {
        if (file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.src = e.target.result;
            img.onload = function() {
                document.getElementById('originalResolution').textContent = `${this.naturalWidth} x ${this.naturalHeight}`;
            };
            previewArea.innerHTML = '';
            previewArea.appendChild(img);
        } else if (file.type.startsWith('video/')) {
            const video = document.createElement('video');
            video.controls = true;
            video.src = e.target.result;
            video.onloadedmetadata = function() {
                document.getElementById('originalResolution').textContent = `${this.videoWidth} x ${this.videoHeight}`;
            };
            previewArea.innerHTML = '';
            previewArea.appendChild(video);
        }
        document.getElementById('originalSize').textContent = formatFileSize(file.size);
        document.getElementById('superResolutionUploadProgress').style.display = 'none';
    };

    reader.readAsDataURL(file);
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function startSuperResolution() {
    const originalPreview = document.getElementById('superResolutionOriginalPreview');
    const resultPreview = document.getElementById('superResolutionResultPreview');

    if (!originalPreview.firstChild) {
        alert('请先上传文件');
        return;
    }

    const upscaleFactor = document.getElementById('upscaleFactor').value;
    const quality = document.getElementById('quality').value;

    console.log(`开始超分辨率重建... 放大倍数: ${upscaleFactor}x, 质量: ${quality}`);
    superResolutionProgressValue = 0;
    document.getElementById('superResolutionProgress').style.display = 'block';

    superResolutionInterval = setInterval(() => {
        if (!superResolutionPaused) {
            superResolutionProgressValue += 10;
            document.getElementById('superResolutionProgress').value = superResolutionProgressValue;

            if (superResolutionProgressValue >= 100) {
                clearInterval(superResolutionInterval);
                document.getElementById('superResolutionProgress').style.display = 'none';

                // 模拟重建结果
                const originalContent = originalPreview.firstChild.cloneNode(true);
                resultPreview.innerHTML = '';
                resultPreview.appendChild(originalContent);

                // 更新分辨率信息
                const originalRes = document.getElementById('originalResolution').textContent.split(' x ');
                const newWidth = parseInt(originalRes[0]) * parseInt(upscaleFactor);
                const newHeight = parseInt(originalRes[1]) * parseInt(upscaleFactor);
                document.getElementById('enhancedResolution').textContent = `${newWidth} x ${newHeight}`;
                
                // 更新文件大小信息
                const originalSize = parseFloat(document.getElementById('originalSize').textContent);
                document.getElementById('enhancedSize').textContent = formatFileSize(originalSize * Math.pow(parseInt(upscaleFactor), 2));

                // 更新对比视图
                updateComparisonView(originalContent.src);
                
                alert('超分辨率重建完成');
            }
        }
    }, 500);
}

function updateComparisonView(imageSrc) {
    const comparisonImage = document.getElementById('comparisonImage');
    comparisonImage.style.backgroundImage = `url(${imageSrc})`;
    
    const comparisonRange = document.getElementById('comparisonRange');
    comparisonRange.addEventListener('input', function() {
        comparisonImage.style.width = this.value + '%';
    });
}

function pauseSuperResolution() {
    superResolutionPaused = true;
    console.log('重建已暂停');
}

function resumeSuperResolution() {
    superResolutionPaused = false;
    console.log('重建已继续');
}

function downloadSuperResolutionResult() {
    const resultPreview = document.getElementById('superResolutionResultPreview');
    if (!resultPreview.firstChild) {
        alert('没有可下载的重建结果');
        return;
    }

    const content = resultPreview.firstChild;
    if (content.tagName === 'IMG') {
        const link = document.createElement('a');
        link.href = content.src;
        link.download = 'super_resolution_result.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        console.log('重建结果已下载');
    } else if (content.tagName === 'VIDEO') {
        alert('视频下载功能尚未实现');
    }
} 